/*
 * This file is part of the MicroPython project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <stdio.h>

#include "py/runtime.h"
#include "py/mphal.h"
#include "extint.h"
#include "pin.h"
#include "keys.h"

#if MICROPY_HW_HAS_KEYS

/// \moduleref pyb
/// \class keys - keys object
///
/// A key object is used to control a push-button keys.
///
/// Usage:
///
///      key = pyb.Keys()       # create a key object
///      key()                    # get state (True if pressed, False otherwise)
///      key.callback(f)          # register a callback to be called when the
///                              #   key is pressed down
///      key.callback(None)       # remove the callback
///
/// Example:
///
///      pyb.Keys().callback(lambda: pyb.LED(1).toggle())

typedef struct _pyb_keys_obj_t {
    mp_obj_base_t base;
    mp_uint_t key_id;
    const pin_obj_t *key_pin;
} pyb_keys_obj_t;

STATIC const pyb_keys_obj_t pyb_keys_obj[] = {
    {{&pyb_keys_type}, 1, MICROPY_HW_KEY1},
    #if defined(MICROPY_HW_KEY2)
    {{&pyb_keys_type}, 2, MICROPY_HW_KEY2},
    #if defined(MICROPY_HW_KEY3)
    {{&pyb_keys_type}, 3, MICROPY_HW_KEY3},
    #endif
    #endif
};

#define NUM_KEYS MP_ARRAY_SIZE(pyb_keys_obj)
// this function inits the keys GPIO so that it can be used
void keys_init0(void) {
    for (int key = 0; key < NUM_KEYS; key++) {
        const pin_obj_t *key_pin = pyb_keys_obj[key].key_pin;
        mp_hal_pin_config(key_pin, MP_HAL_PIN_MODE_INPUT, MICROPY_HW_KEYS_PULL, 0);
    }
}

int keys_get(mp_uint_t key) {
    int val = ((pyb_keys_obj[key-1].key_pin->gpio->IDR & pyb_keys_obj[key-1].key_pin->pin_mask) != 0);
    return val == MICROPY_HW_KEYS_PRESSED;
}

/******************************************************************************/
// MicroPython bindings


void key_obj_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
    pyb_keys_obj_t *self = MP_OBJ_TO_PTR(self_in);
    mp_printf(print, "KEY(%u)", self->key_id);
}


/// \classmethod \constructor(id)
/// Create an KEY object associated with the given KEY:
///
///   - `id` is the KEY number, 1-4.
STATIC mp_obj_t key_obj_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
    // check arguments
    mp_arg_check_num(n_args, n_kw, 1, 1, false);

    // get key number
    mp_int_t key_id = mp_obj_get_int(args[0]);

    // check key number
    if (!(1 <= key_id && key_id <= NUM_KEYS)) {
        mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("KEY(%d) doesn't exist"), key_id);
    }

    // return static key object
    return MP_OBJ_FROM_PTR(&pyb_keys_obj[key_id - 1]);
}

/// \method \call()
/// Return the keys state: `True` if pressed down, `False` otherwise.
mp_obj_t pyb_keys_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
    pyb_keys_obj_t *self = MP_OBJ_TO_PTR(self_in);
    // get key state
    mp_arg_check_num(n_args, n_kw, 0, 0, false);
    //printf("==>%s",args[n_args-1]);
    return keys_get(self->key_id) ? mp_const_true : mp_const_false;
}

mp_obj_t pyb_keys_value(mp_obj_t self_in) {
    pyb_keys_obj_t *self = MP_OBJ_TO_PTR(self_in);
    //(void)self_in;
    return mp_obj_new_bool(keys_get(self->key_id));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_keys_value_obj, pyb_keys_value);

STATIC mp_obj_t keys_callback(mp_obj_t line) {
    if (MP_STATE_PORT(pyb_keys_callback) != mp_const_none) {
        mp_call_function_0(MP_STATE_PORT(pyb_keys_callback));
    }
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(keys_callback_obj, keys_callback);

/// \method callback(fun)
/// Register the given function to be called when the key is pressed down.
/// If `fun` is `None`, then it disables the callback.
mp_obj_t pyb_keys_callback(mp_obj_t self_in, mp_obj_t callback) {
    pyb_keys_obj_t *self = MP_OBJ_TO_PTR(self_in);
    MP_STATE_PORT(pyb_keys_callback) = callback;
    // Init the EXTI each time this function is called, since the EXTI
    // may have been disabled by an exception in the interrupt, or the
    // user disabling the line explicitly.
    //extint_register(MP_OBJ_FROM_PTR(MICROPY_HW_KEYS_PIN),
    extint_register(MP_OBJ_FROM_PTR(pyb_keys_obj[self->key_id-1].key_pin),
        MICROPY_HW_KEYS_EXTI_MODE,
        MICROPY_HW_KEYS_PULL,
        callback == mp_const_none ? mp_const_none : MP_OBJ_FROM_PTR(&keys_callback_obj),
        true);
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_keys_callback_obj, pyb_keys_callback);


STATIC const mp_rom_map_elem_t pyb_keys_locals_dict_table[] = {
    { MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&pyb_keys_value_obj) },
    { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&pyb_keys_callback_obj) },
};

STATIC MP_DEFINE_CONST_DICT(pyb_keys_locals_dict, pyb_keys_locals_dict_table);

MP_DEFINE_CONST_OBJ_TYPE(
    pyb_keys_type,
    MP_QSTR_Keys,
    MP_TYPE_FLAG_NONE,
    make_new, key_obj_make_new,
    print, key_obj_print,
    call, pyb_keys_call,
    locals_dict, &pyb_keys_locals_dict
    );

MP_REGISTER_ROOT_POINTER(mp_obj_t pyb_keys_callback);
#else
    // For boards with no KEYS, we leave an empty function here so that we don't
    // have to put conditionals everywhere.
    void keys_init(void) {
    }
    int keys_get(mp_uint_t key) {
        return 0;
    }

#endif // MICROPY_HW_HAS_KEYS
